package com.liukai.exam.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liukai.exam.common.Result;
import com.liukai.exam.mapper.menu.MenusMapper;
import com.liukai.exam.pojo.ClassInfo;
import com.liukai.exam.pojo.SysUser;
import com.liukai.exam.pojo.menu.Menus;
import com.liukai.exam.service.IClassInfoService;
import com.liukai.exam.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author liu kai
 * @since 2021-02-01
 */
@RestController
@RequestMapping("/exam/sysUser")
@Slf4j
public class SysUserController {


    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private MenusMapper menusMapper;

    @Autowired
    private IClassInfoService iClassInfoService;

    /**
     * 登录
     *
     * @param sysUser
     * @return
     */
    @PostMapping(value = "/login")
    public Result login(@RequestBody SysUser sysUser) {

        log.info(sysUser.toString());

        Result result;

//        SysUser sysUser = new SysUser();
//        sysUser.setUserId(2018081322L);
//        sysUser.setUserPwd("2018081322");
//        sysUser.setSchoolName("成都信息工程大学");

        SysUser login = iSysUserService.login(sysUser);

//        if (login == null) {
//            log.info("========>NULL");
//        }else{
//            log.info("=================>" + login.toString());
//        }

        // TODO 需要判断userId，classId，pwd都不为空
        if (login == null) {
            result = Result.fail(404, "登录失败", login);
            log.info("==============getUser====>NULL");
        } else {
            log.info("==============getUser====>" + login.toString());
            result = Result.succ(200, "登录成功", login);
        }

        return result;
    }

    /**
     * 注册
     *
     * @param sysUser
     * @return
     */
    @PostMapping(value = "/register")
    public Result register(@RequestBody SysUser sysUser) {
        if (sysUser == null) {
            log.info("==============sysUser====>NULL");
        } else {
            log.info("==============sysUser====>" + sysUser.toString());
        }
        Result result = Result.fail("失败");

        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.setEntity(sysUser);

        SysUser getUser = iSysUserService.getOne(wrapper);

        if (getUser == null) { // getUser为空，允许注册
            boolean save = iSysUserService.save(sysUser);
            log.info(save + "");
            if (save) {
                result = Result.fail(200, "注册成功", sysUser);
                log.info("==============getUser====>NULL");
            } else {
                result = Result.fail(404, "注册失败", getUser);
                log.info("==============getUser====>NULL");
            }
        } else { // getUser为空，不允许注册
            log.info("==============getUser====>" + getUser.toString());
            result = Result.fail(404, "注册失败", getUser);
        }

        return result;
    }

    /**
     * 获取侧边栏菜单
     *
     * @param roleId
     * @return
     */
    @GetMapping(value = "/getMenuList/{roleId}")
    public Result getMenuList(@PathVariable("roleId") Integer roleId) {

        List<Menus> menus = menusMapper.getMenusByRole(roleId);

        Result result = Result.succ(200, "获取菜单成功", menus);

        return result;
    }

    /**
     * 获取个人信息
     *
     * @param userId
     * @param classId
     * @return
     */
    @GetMapping(value = "/getPersonalInfoById/{userId}/{classId}")
    public Result getPersonalInfoById(@PathVariable Long userId, @PathVariable Integer classId) {

        ClassInfo classInfo = iClassInfoService.getClassInfoByClassId(classId);
        SysUser sysUser = iSysUserService.getUserInfoById(userId, classId);

        if (classInfo != null && sysUser != null) {
            HashMap<String, Object> data = new HashMap<>();
            data.put("classInfo", classInfo);
            data.put("sysUser", sysUser);
            Result result = Result.succ(200, "获取个人信息成功", data);
            return result;
        } else {
            Result result = Result.fail(404, "获取个人信息失败", null);
            return result;
        }
    }

    /**
     * 获取账号信息
     *
     * @param userId
     * @param classId
     * @return
     */
    @GetMapping(value = "/getIdInfoById/{userId}/{classId}")
    public Result getIdInfoById(@PathVariable Long userId, @PathVariable Integer classId) {

        SysUser sysUser = iSysUserService.getUserInfoById(userId, classId);

        if (sysUser != null) {
            Result result = Result.succ(200, "获取账号信息成功", sysUser);
            return result;
        } else {
            Result result = Result.fail(404, "获取账号信息失败", null);
            return result;
        }
    }

    /**
     * 修改用户信息
     *
     * @param sysUser
     * @return
     */
    @PutMapping(value = "/updateIdInfoById")
    public Result updateIdInfoById(@RequestBody SysUser sysUser) {

        int count = iSysUserService.updateUserInfoById(sysUser);

        if (count > 0) {
            Result result = Result.succ(200, "修改账号信息成功", null);
            return result;
        } else {
            Result result = Result.fail(404, "修改账号信息失败", null);
            return result;
        }
    }


    /**
     * 上传头像
     *
     * @param file
     * @param userId
     * @param classId
     * @return
     */
    @PostMapping(value = "/upLoadHeadImg")
    public Result upLoadHeadImg(@RequestParam(value = "file") MultipartFile file, Long userId, Integer classId) {

        log.info(userId + ":" + classId);

        int count = iSysUserService.updateHeadImgById(file, userId, classId);

        log.info(count + "");

        if (count > 0) {
            Result result = Result.succ(200, "修改用户头像成功", null);
            return result;
        } else {
            Result result = Result.fail(404, "修改用户头像失败", null);
            return result;
        }
    }

    /**
     * 获取头像
     *
     * @param headImg
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getHeadImgByUrl/{headImg}")
    public ResponseEntity<byte[]> getHeadImgByUrl(@PathVariable("headImg") String headImg) throws Exception {
        return iSysUserService.getHeadImgByUrl(headImg);
    }


}

